package cn.samler.account_manager.controller;

import cn.samler.account_manager.annotation.InAccountFailedMap;
import cn.samler.account_manager.model.Page;
import cn.samler.account_manager.model.Response;
import cn.samler.account_manager.model.req.AccountAddRequest;
import cn.samler.account_manager.model.req.AccountUpdateRequest;
import cn.samler.account_manager.service.AccountService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;

@RestController
@RequestMapping("account")
public class AccountController {
    private final AccountService accountService;

    public AccountController(AccountService accountService) {
        this.accountService = accountService;
    }

    /**
     * 添加账号
     *
     * @param request {@link AccountAddRequest}
     * @return {@link Response}
     */
    @PutMapping("")
    public Response add(@RequestBody @Validated AccountAddRequest request) {
        return accountService.add(request);
    }

    /**
     * 删除账号
     *
     * @param id account id
     * @return {@link Response}
     */
    @DeleteMapping("{id}")
    public Response delete(@PathVariable @Valid @NotNull(message = "参数错误") @Positive(message = "id有误") Integer id) {
        return accountService.delete(id);
    }

    /**
     * 更新账号数据
     *
     * @param request {@link AccountUpdateRequest}
     * @return {@link Response}
     */
    @PostMapping("")
    public Response update(@RequestBody @Validated AccountUpdateRequest request) {
        return accountService.update(request);
    }

    /**
     * 查询账号列表
     *
     * @param page 页数
     * @param offset 每页数据量
     * @return {@link Response}
     */
    @GetMapping("list")
    public Response list(@RequestParam @Positive(message = "页数错误") Integer page,
                         @RequestParam @Positive(message = "偏移量错误") Integer offset) {
        Page p = new Page();
        p.setPage(page);
        p.setOffset(offset == null ? 10 : offset);

        return accountService.list(p);
    }

    /**
     * 搜索账号
     *
     * @param type 搜索字段
     * @param keyword 搜索内容
     * @return {@link Response}
     */
    @GetMapping("search")
    public Response search(@RequestParam @Positive(message = "页数错误") Integer page,
                           @RequestParam @Positive(message = "偏移量错误") Integer offset,
                           @RequestParam @Valid @InAccountFailedMap(message = "查找类型有误") Integer type,
                           @RequestParam @Valid @NotNull(message = "查询不能为空") Object keyword) {
        return accountService.search(page, offset, type, keyword);
    }
}
